package cn.claim.storage.tools;

import cn.claim.storage.tools.FileInfoData;
import cn.claim.storage.tools.JSONParsable;
import cn.claim.storage.tools.NodeData;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Objects;
import java.util.Scanner;

import static cn.claim.storage.tools.Config.*;

/**
 * Created by claim on 17-7-13.
 */
public final class InfoHandler {

    private String communicate(String order, String data) {
        Socket socket = null;
        try {
            socket = new Socket(getProp("ip", "localhost"),
                    Integer.parseInt(getProp("fileServerPort", "6500")));
            Scanner response = new Scanner(socket.getInputStream());
            PrintWriter request = new PrintWriter(socket.getOutputStream());

            request.println(order);
            request.println(data);
            request.flush();

            String result = response.nextLine();
            if (Objects.equals(result, "null"))
                return null;
            else return result;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public boolean registerFile(FileInfoData info) {
        return communicate("upload", info.toJSON()) != null;
    }

    public FileInfoData getFileInfo(String uuid) {
        String data = communicate("file", uuid);
        if (data == null)
            return null;
        else
            return JSONParsable.parse(data, FileInfoData.class);
    }

    public NodeData getNodeInfo(NodeData extract) {
        String data = communicate("node", extract == null ? "null" : extract.toJSON());
        if (data == null)
            return null;
        else
            return JSONParsable.parse(data, NodeData.class);
    }

    public NodeData getNodeInfo(String nodeName) {
        String data = communicate("nodeInfo", nodeName);
        if(data==null)
            return null;
        else
            return JSONParsable.parse(data,NodeData.class);
    }

    public boolean deleteFile(String uuid) {
        return JSONParsable.parse(communicate("delete", uuid), boolean.class);
    }

}
